package day1;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

public class RedisDemo {
    static Jedis j=new Jedis("192.168.188.100",6379);

    @Test
    public void m1(){
        j.set("address","南京");
        System.out.println(j.get("address"));
        j.incr("age");
        Set<String>keys= j.keys("*");
//        for (String k : keys) {
//
//        }

        keys.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        });
        //jdk8新特性
        keys.forEach(k-> System.out.println(k));
        Map<String,String>m=new HashMap<>();
        m.put("u1","a1");
        m.put("u2","a2");
        j.hset("users","u3","a3");
        j.hmset("users",m);
        System.out.println(j.hgetAll("users"));
    }

    @Test
    public void transac()throws Exception{
        j.set("money","960");//你的可用额度是960
        j.set("debt","40");//欠债

        int consum=10;

        j.watch("money");
        Thread.sleep(10000);
        int money=Integer.parseInt(j.get("money"));

        //信用卡额度不够
        if(money<consum){
            j.unwatch();
            return;
        }

        System.out.println("*********************开启事务************************");
        Transaction t = j.multi();
        t.incrBy("debt",consum);
        t.decrBy("money",consum);
        List<Object> list = t.exec();
        if(list==null){
            System.out.println("事务失败");
        }
        j.unwatch();
        System.out.println("当前余额:"+j.get("money")+",欠账:"+j.get("debt"));
        ConcurrentHashMap c=new ConcurrentHashMap();
        c.put("key","value");
        Hashtable h=new Hashtable();
        h.put(null,null);
    }

    //主从复制
    @Test
    public void master_slave(){
        Jedis master=new Jedis("192.168.188.100",6379);
        Jedis slave=new Jedis("192.168.188.100",6380);
        slave.slaveof("192.168.188.100",6379);

        master.set("driver","com.mysql.Driver");
        System.out.println(slave.get("driver"));
        master.close();
        slave.close();

    }
}
